INCLUDES = -I src
CC = gcc
CFLAGS = -g
CPPFLAGS =
COMPILE.c = $(CC) $(CFLAGS) $(INCLUDES) $(CPPFLAGS) $(TARGET_ARCH) -c
OUTPUT_OPTION = -o $@

MKDIR := mkdir -p
RM := rm -rf

srcdir = src
objdir = bin
depdir = $(srcdir)/.d

fat32_objs = $(objdir)/format_fat32.o \
			 $(objdir)/pre_allocation_fat32.o \
			 $(objdir)/cyclic_write_fat32.o \
			 $(objdir)/test_fat32.o \
			 $(objdir)/fat32.o \
			 $(objdir)/initialise_fat32.o \
			 $(objdir)/recover_fat32.o

fat32_hdrs = ourhdr.h fat32.h

ext2_objs = $(objdir)/format_ext2.o \
			$(objdir)/pre_allocation_ext2.o \
			$(objdir)/test_ext2.o \
			$(objdir)/ext2.o

ext2_hdrs = ourhdr.h ext2.h

sources = $(shell find $(srcdir) -name "*.c")
objects = $(subst $(srcdir),$(objdir),\
		  	$(subst .c,.o, $(sources)))
dependents = $(subst .c,.d,\
			 	$(subst $(srcdir),$(depdir), $(sources)))

all: test_fat32 test_ext2 tools

test_fat32: $(objdir)/test_fat32

test_ext2: $(objdir)/test_ext2

$(objdir)/test_fat32 : $(fat32_objs) $(objdir)/libs.o
	$(LINK.o) $^ $(LOADLIBS) $(LDLIBS) $(OUTPUT_OPTION)

$(objdir)/test_ext2 : $(ext2_objs) $(objdir)/libs.o
	$(LINK.o) $^ $(LOADLIBS) $(LDLIBS) $(OUTPUT_OPTION)

$(objects) : $(objdir)/%.o : $(srcdir)/%.c
	@$(MKDIR) $(objdir)
	$(COMPILE.c) $< $(OUTPUT_OPTION)

-include $(dependents)

$(dependents) : $(srcdir)/.d/%.d : $(srcdir)/%.c
	@$(MKDIR) $(srcdir)/.d/; 	\
	$(CC) -M $(CPPFLAGS) $< > $@.$$$$; \
	sed 's,\(.*\)\.o[ :]*,$(objdir)/\1.o $@ : ,g' < $@.$$$$ > $@; \
	rm -f $@.$$$$


tools_dir = tools
tools_sources = $(shell find $(tools_dir) -name "*.c")
tools_objdir = $(objdir)/tools
tools_objects = $(addprefix $(tools_objdir)/,\
					$(subst .c,,\
						$(subst $(tools_dir)/,, $(tools_sources))))

tools : $(tools_objects)
	@echo Followings are useful tools:
	@echo $(tools_objects) | sed 's, ,\n,g' | sed 's,^,    ,';

$(tools_objdir)/fat32tools: CPPFLAGS+=-DDEBUG

$(tools_objects) : $(tools_objdir)/% : $(tools_dir)/%.c
	@$(MKDIR) $(tools_objdir)
	$(CC) $(CFLAGS) $(CPPFLAGS) $(INCLUDES) $< -o $@

.PHONY: clean tools test_ext2 test_fat32 all

clean: 
	$(RM) $(objdir)
	$(RM) $(depdir)





